package com.lyeducation.entities.base;

import com.lyeducation.core.base.TreeEntityService.EntryTreeService;
import com.lyeducation.util.StringUtils;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import java.util.Comparator;
import java.util.Objects;
import java.util.TreeSet;

@MappedSuperclass
public abstract class BaseTreeEntity<E extends BaseTreeEntity> extends BaseDataEntity implements EntryTreeService<E, String> {
    private String parentId;
    private TreeSet<E> children;
    //  同级排序
    private int sort;

    @Override
    @Column(name = "parentId", nullable = true, length = 18)
    public String getParentId() {
        return this.parentId;
    }

    @Override
    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    @Override
    @Transient
    public TreeSet<E> getChildren() {
        return this.children;
    }

    @Override
    public void setChildren(TreeSet<E> children) {
        if (children == null) {
            children =
                    new TreeSet<E>(
                            new Comparator<E>() {
                                @Override
                                public int compare(E o1, E o2) {
                                    if (!StringUtils.equals(o1.getParentId(), o2.getParentId())) {
                                        throw new RuntimeException("同一级别添加错误");
                                    }
                                    if (o1.getId().equals(o2.getId())) {
                                        return 0;
                                    }
                                    int sort = o1.getSort() - o2.getSort();
                                    if (sort == 0) {
                                        return 1;
                                    }
                                    return sort;
                                }
                            });
        }
        this.children = children;
    }

    @Override
    @Basic
    @Column(name = "sort", nullable = false, length = 8)
    public int getSort() {
        return 0;
    }

    @Override
    public void setSort(int sort) {
        this.sort = sort;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        if (!super.equals(o)) {
            return false;
        }
        BaseTreeEntity<?> that = (BaseTreeEntity<?>) o;
        return sort == that.sort &&
                Objects.equals(parentId, that.parentId) &&
                Objects.equals(children, that.children);
    }

    @Override
    public int hashCode() {

        return Objects.hash(super.hashCode(), parentId, children, sort);
    }
}
